package com.wangsd.web.coupon.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wangsd.web.coupon.entity.Category;
import com.wangsd.web.coupon.entity.Company;
import com.wangsd.web.coupon.mapper.CategoryMapper;
import com.wangsd.web.coupon.service.CategoryService;
import com.wangsd.web.coupon.service.CompanyService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author generator
 * @since 2019-09-20
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Resource
    CategoryMapper categoryMapper;

    @Autowired
    CompanyService companyService;

    @Override
    public void addOrUpdate(Category category) {

        if(category.getCode()==null){
            Company company = companyService.getById(category.getCompanyId());
            category.setCode(company.getCode());
        }

        if (category.getId() != null) {
            categoryMapper.updateById(category);
        } else {
            categoryMapper.insert(category);
        }
    }

    @Override
    public IPage<Category> selectPage(String code, Integer pageNum, Integer pageSize, Category category) {
        Page<Category> page = new Page<>(pageNum, pageSize);
        IPage<Category> resultIPage = categoryMapper.selectListXml(page, code, category);
        return resultIPage;
    }

    @Override
    public List<Map<String, Object>> selectAllByUserCode(String code) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        QueryWrapper queryWrapper = new QueryWrapper();
        if (StringUtils.isNotBlank(code)) {
            queryWrapper.likeRight("code", code);
        }
        List<Category> list = categoryMapper.selectList(queryWrapper);
        for (Category category : list) {
            Map<String, Object> map = new HashMap();
            map.put("code", category.getCode());
            map.put("id", category.getId());
            map.put("name", category.getName());
            resultList.add(map);
        }
        return resultList;
    }

    @Override
    public Category selectRepeat(String name, Long id, Long companyId) {
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", name).eq("company_id", companyId);
        if (id != null) {
            queryWrapper.ne("id", id);
        }
        return categoryMapper.selectOne(queryWrapper);
    }
}
